#include <iostream>
#include "Log.hpp"
// OS
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

enum // 匿名
{
    SOCK_ERR = 1,
    BIND_ERR,
    ACCEPT_ERR,
    READ_ERR,
    WRITE_ERR,
    CONNECT_ERR
};

//./client serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage: ./xxx serverip serverport" << std::endl;
        exit(-1);
    }
    std::string ser_ip = argv[1];
    uint16_t ser_port = std::stoi(argv[2]);

    // OS自动bind

    // 打开网卡
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        LOG(FATAL, "sockfd fail");
        exit(SOCK_ERR);
    }

    // 发起连接
    struct sockaddr_in ser_socket;
    uint len = sizeof(ser_socket);
    ser_socket.sin_family = AF_INET;
    ser_socket.sin_port = htons(ser_port);
    inet_pton(AF_INET, ser_ip.c_str(), &ser_socket.sin_addr.s_addr);
    //LOG(INFO, "111111");
    int re = connect(sockfd, (struct sockaddr *)&ser_socket, len);
    if (re < 0)
    {
        LOG(FATAL, "connet fail");
        exit(CONNECT_ERR);
    }
    //LOG(INFO, "2222222");

    while (1)
    {
        // 写
        std::string message;
        std::cout << "Enter#";
        std::getline(std::cin, message);
        //LOG(INFO, "333333");
        int w_n = ::write(sockfd, message.c_str(), message.size());
        if (w_n >= 0)
        {
            // 读
            //LOG(INFO, "444444444");
            char echo_buffer[1024] = {0};
            int r_n = ::read(sockfd, echo_buffer, sizeof(echo_buffer));
            if (r_n > 0)
            {
                std::cout << echo_buffer << std::endl;
            }
            else 
            {
                LOG(WARNING, "read return <=0, break");
                break;
            }
            // else //(r_n < 0)
            // {
            //     LOG(FATAL, "read fail");
            //     exit(READ_ERR);
            // }
        }
        else // (w_n < 0)
        {
            LOG(FATAL, "write fail");
            exit(WRITE_ERR);
        }
    }

    ::close(sockfd);

    return 0;
}